package lesson2.example5;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

interface IVehical {
    void run();
}
 
 
class Car implements IVehical {
    public void run() {
        System.out.println("Car会跑");
    }
}
 
class VehicalInvacationHandler implements InvocationHandler {
  
    private final IVehical vehical;
    public VehicalInvacationHandler(IVehical vehical){
        this.vehical = vehical;
    }
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("---------before-------");
        Object invoke = method.invoke(vehical, args);
        System.out.println("---------after-------");
  
        return invoke;
    }
}
 
public class TestProxy {
    public static void main(String[] args) {
        IVehical car = new Car();
  
        // 代理对象
        IVehical vehical = (IVehical)Proxy.newProxyInstance(
	                        car.getClass().getClassLoader(), 
	                        Car.class.getInterfaces(), 
	                        new VehicalInvacationHandler(car)
                        );
        // 调用run()方法其实调用的是VehicalInvacationHandler.invoke()方法
        vehical.run();
    }
}
